window.onload = function(){
    var form = document.querySelector('form')
    var usernameInput = document.querySelector('[name="username"]')
    var passwordInput = document.querySelector('[name="password"]')
    var repassInput = document.querySelector('[name="repass"]')
    var emailInput = document.querySelector('[name="email"]')
    form.onsubmit = function () {
        // console.log(usernameInput.value);
        // console.log(passwordInput.value);
        // console.log(repassInput.value);
        // console.log(emailInput.value);

        var usernameReg = /^[\u4E00-\u9FA5\uF900-\uFA2D|\w]{2,15}$/
        if (!usernameReg.test(usernameInput.value)) {
            alert('用户名不符合规则')
            return false
        }
        var passwordReg = /^.{6,10}$/
        if (!passwordReg.test(passwordInput.value)) {
            alert('密码不符合规则')
            return false
        }
        if (passwordInput.value != repassInput.value) {
            alert('两次密码输入不一致')
            return false
        }
        var emailReg = /(^[1-9]\d{5,9}@(qq|QQ)\.com$)|(^[a-zA-Z]\w{5,17}@((126|163)\.com|yeah\.net)$)/
        if (!emailReg.test(emailInput.value)) {
            alert('邮箱不符合规则')
            return false
        }

        // var xhr = new XMLHttpRequest()
        // xhr.open("post", "/front/api/users/register")
        // // 设置请求头
        // xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
        // // 发送对应请求
        // xhr.send(`username=${usernameInput.value}&password=${passwordInput.value}&email=${emailInput.value}`)
        // xhr.onreadystatechange = function () {
        //     if (xhr.readyState === 4) {
        //         if (xhr.status >= 200 && xhr.status < 300) {
        //             var res = xhr.responseText;
        //             // res.json()
        //             res = JSON.parse(res)
        //             var { error_code, msg } = res
        //             alert(msg)
        //             if (error_code === 0) {
        //                 location.href = './login.html'
        //             }
        //             console.log(res);
        //         }
        //     }
        // }


        request({
            url: "/front/api/users/register",
            method: 'post',
            data: {
                username: usernameInput.value,
                password: passwordInput.value,
                email: emailInput.value
            },
            success(res) {
                var { error_code, msg } = res
                alert(msg)
                if (error_code === 0) {
                    location.href = './login.html'
                }
                console.log(res);
            },
            error(){
                console.log("网络请求失败！");
            }
        })

        return false
    }

}